class QuestionsController < ApplicationController
  before_filter :login_required, :except => :index
  
  before_filter :load_questionnaire
  
  def load_questionnaire
    @questionnaire = Questionnaire.find(params[:questionnaire_id])
  end
  
  # GET /questions
  # GET /questions.xml
  def index
    @questions = @questionnaire.questions.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @questions }
      format.json { render :json => @questions}
    end
  end

  # GET /questions/1
  # GET /questions/1.xml
  def show
    @question = @questionnaire.questions.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @question }
    end
  end

  # GET /questions/new
  # GET /questions/new.xml
  def new
    @question = @questionnaire.questions.build

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @question }
    end
  end

  # GET /questions/1/edit
  def edit
    @question = @questionnaire.questions.find(params[:id])
  end

  # POST /questions
  # POST /questions.xml
  def create
    @question = @questionnaire.questions.new(params[:question])

    respond_to do |format|
      if @question.save
        format.html { redirect_to([@questionnaire, @question], :notice => 'Question was successfully created.') }
        format.xml  { render :xml => @question, :status => :created, :location => @question }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @question.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /questions/1
  # PUT /questions/1.xml
  def update
    @question = @questionnaire.questions.find(params[:id])

    respond_to do |format|
      if @question.update_attributes(params[:question])
        format.html { redirect_to([@questionnaire, @question], :notice => 'Question was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @question.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /questions/1
  # DELETE /questions/1.xml
  def destroy
    @question = @questionnaire.questions.find(params[:id])
    @question.destroy

    respond_to do |format|
      format.html { redirect_to(questionnaire_questions_url(@questionnaire)) }
      format.xml  { head :ok }
    end
  end
end
